/*
 * $Id: ScopedPtr.hpp 59 2009-02-19 10:30:57Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#ifndef _XP_SCOPEDPTR_CLASS_
#define _XP_SCOPEDPTR_CLASS_

#include <xp/Uncopyable.hpp>
#include <xp/bas/assert.h>

XP_BEGIN_NAMESPACE (xp)

template <typename T>
struct ScopedPtrDeleter
{
	void operator() (T* ptr, void* arg)
	{
		delete ptr;
	}
};

template <typename T>
struct ScopedPtrArrayDeleter
{
	void operator() (T* ptr, void* arg)
	{
		delete[] ptr;
	}
};


template<typename T, typename DELETER = ScopedPtrDeleter<T> >
class ScopedPtr: public Uncopyable
{
public:
	typedef ScopedPtrDeleter<T> DefaultDeleter;

	ScopedPtr (T* ptr = (T*)XP_NULL, void* darg = (void*)XP_NULL) 
	{
		this->_ptr = ptr;
		this->_darg = darg;
	}

	~ScopedPtr () 
	{
		if (this->_ptr) 
		{
			this->deleter (this->_ptr, this->_darg);
		}
	}

	T& operator* ()
	{
		XP_ASSERT (this->_ptr != (T*)XP_NULL);
		return *this->_ptr;
	}
	
	const T& operator* () const 
	{
		XP_ASSERT (this->_ptr != (T*)XP_NULL);
		return *this->_ptr;
	}

	T* operator-> () 
	{
		XP_ASSERT (this->_ptr != (T*)XP_NULL);
		return this->_ptr;
	}

	const T* operator-> () const 
	{
		XP_ASSERT (this->_ptr != (T*)XP_NULL);
		return this->_ptr;
	}

	bool operator! () const 
	{
		return this->_ptr == (T*)XP_NULL;
	}

	T& operator[] (xp_size_t idx) 
	{
		XP_ASSERT (this->_ptr != (T*)XP_NULL);
		return this->_ptr[idx];
	}

	T* get () 
	{
		return this->_ptr;
	}

	const T* get () const
	{
		return this->_ptr;
	}

	T* release () 
	{
		T* t = this->_ptr;
		this->_ptr = (T*)XP_NULL;
		this->_darg = XP_NULL;
		return t;
	}

	void reset (T* ptr = (T*)XP_NULL, void* darg = (T*)XP_NULL) 
	{
		if (this->_ptr) 
		{
			this->deleter (this->_ptr, this->_darg);
		}

		this->_ptr = ptr;
		this->_darg = darg;
	}

protected:
	T* _ptr;
	void* _darg;
	DELETER deleter;
}; 

XP_END_NAMESPACE (xp)

#endif
